﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bzure.Common.Core;
using Bzure.Common.Patterns;

namespace System
{
    public static class ApplicationStartContextDecoratorExtensions
    {
        internal static Dictionary<Type, Delegate> decoratorBuilders = new Dictionary<Type, Delegate>();
        static List<Delegate> list = new List<Delegate>();
        public static void SetContractDecorator<T>(this IApplicationStartContext StartContext, Func<IDecorate<T>> decoratorBuilder)
            where T : class
        {
            decoratorBuilders[typeof(T)] = decoratorBuilder;
            list.Add(decoratorBuilder);
        }
        public static Func<IDecorate<T>> GetContractDecoratorBuilder<T>(this Public Public) where T : class
        {
            Delegate hander = null;
            if (decoratorBuilders.TryGetValue(typeof(T), out hander))
            {
                return hander as Func<IDecorate<T>>;
            }
            return default(Func<IDecorate<T>>);
        }
        public static T AsDecorator<T>(this T source) where T : class
        {
            //if (source is IDecorate<T>)
            //    return source;
            T result = source;
            Func<IDecorate<T>> builder = Actor.Public.GetContractDecoratorBuilder<T>();
            if (builder.IsNotNull())
            {
                IDecorate<T> decorator = builder();
                decorator.InitDecorator(result);
                if (decorator is T)
                    result = decorator as T;
            }
            return result;
        }
    }
}
